package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.controller.EmployeeController;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import com.sun.el.lang.ELArithmetic;
import com.sun.org.apache.xpath.internal.operations.Or;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
   @Autowired
    private ShoppingCartService shoppingCartService;
   @Autowired
    private AddressBookService addressBookService;
   @Autowired
    private UserService userService;
   @Autowired
    private OrderDetailService orderDetailsService;

    @Override
    public void submit(Orders orders) {
        log.info("[OrderServiceImpl:{}]",orders);
        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        List<ShoppingCart>shoppingCarts=shoppingCartService.list(wrapper);
        if ( shoppingCarts ==null ||shoppingCarts.size()==0){
            throw new CustomException("购物车不能为空");
        }//查询地址数据
       AddressBook addressBook=addressBookService.getById(orders.getAddressBookId());
        if (addressBook==null){
            throw new CustomException("收货地址有误,不能下单");
        }
        long orderId = IdWorker.getId();
        //生成唯一的订单号
        AtomicInteger amount = new AtomicInteger(0);
        //计算订单的总价值
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item,orderDetail,"orderId");
            orderDetail.setOrderId(orderId);
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
           return orderDetail;
        }).collect(Collectors.toList());
        log.info("订单列表:{}",orderDetails);
        //组装订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());//订单时间
        orders.setCheckoutTime(LocalDateTime.now());//结账时间
        orders.setStatus(2);//状态
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(BaseContext.getCurrentId());
        orders.setNumber(String.valueOf(orderId));
        //获取用户的名字
        User user=userService.getById(BaseContext.getCurrentId());
        orders.setUserName(user.getName());
        //设置 收货人 电话和地址
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向单表中插入数据  单条数据
        this.save(orders);
        //向订单明细表中出入数据   多条数据
        orderDetailsService.saveBatch(orderDetails);

        //清空购物车
        shoppingCartService.remove(wrapper);

    }
}
